define(function () {
  /**
   * 椭圆标绘
   * @param {Cesium.Viewer} viewer 基本视图
   * @param {Cesium.ScreenSpaceEventHandler} handler 屏幕监听事件
   * @param {Cesium.CustomDataSource} plotEntities 标绘实体集合
   */
  let ellipsePlotting = function (viewer, handler, plotEntities) {
    let semiMajorAxis                                 //长半轴
    let semiMinorAxis                                 //短半轴
    let startCartesian                                //开始点笛卡尔坐标
    let endCartesian                                  //结束点笛卡尔坐标

    //椭圆标绘开始，锁定转动
    viewer.scene.screenSpaceCameraController.enableRotate = false

    /**
     *添加椭圆实体
     *@param {Cesium.Cartesian3} positionData 椭圆中心
     */
    function drawShape(positionData) {
      return plotEntities.entities.add({
        description: 'plot',
        ellipse: {
          semiMajorAxis: semiMajorAxis,
          semiMinorAxis: semiMinorAxis,
          height: 0,
          fill: true,
          outline: true,
          outlineColor: Cesium.Color.BLACK,
          material: Cesium.Color.RED.withAlpha(0.5)
        },
        position: positionData
      })
    }

    //左键按下，赋值开始点坐标
    handler.setInputAction((event) => {
      startCartesian = viewer.camera.pickEllipsoid(event.position, viewer.scene.globe.ellipsoid)
    }, Cesium.ScreenSpaceEventType.LEFT_DOWN)

    //左键松下，获得结束点坐标 计算并绘画
    handler.setInputAction(function (event) {

      //是否松下左键既可以转动
      //viewer.scene.screenSpaceCameraController.enableRotate = true

      endCartesian = viewer.camera.pickEllipsoid(event.position, viewer.scene.globe.ellipsoid)

      let centerCartesian = new Cesium.Cartesian3((startCartesian.x + endCartesian.x) / 2, (startCartesian.y + endCartesian.y) / 2, (startCartesian.z + endCartesian.z) / 2)
      let nearAngle = new Cesium.Cartesian3(startCartesian.x, endCartesian.y, centerCartesian.z)
      semiMajorAxis = Cesium.Cartesian3.distance(startCartesian, nearAngle) / 2
      semiMinorAxis = Cesium.Cartesian3.distance(endCartesian, nearAngle) / 2

      //长半轴必须大于短半轴
      if (semiMajorAxis < semiMinorAxis) {
        [semiMajorAxis, semiMinorAxis] = [semiMinorAxis, semiMajorAxis]
      }
      drawShape(centerCartesian)

      //初始化椭圆数据
      semiMinorAxis = undefined
      semiMinorAxis = undefined

    }, Cesium.ScreenSpaceEventType.LEFT_UP)

    //右键点击，取消锁定转动
    handler.setInputAction((event) => {
      viewer.scene.screenSpaceCameraController.enableRotate = true
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK)
  }
  return ellipsePlotting
})